package HOT;

/**
 * Author  zxy
 * Date  2023/6/21 下午 4:29
 */
public class DaysBetweenDates {

    // 判断闰年
    public boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }

    // 日期转换为整数
    public int convertDateToInt(String date) {
        String[] dateNum = date.split("-");

        int year = Integer.parseInt(dateNum[0]);
        int month = Integer.parseInt(dateNum[1]);
        int day = Integer.parseInt(dateNum[2]);

        // 总的天数
        int cnt = 0;

        // 每月天数
        int[] monthDays = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        // 计算当年总天数
        for (int i = 1; i < month; i++) {
            cnt += monthDays[i - 1];
        }
        cnt += day;

        // 当年是闰年则加一天且大于2月
        if (isLeapYear(year) && month > 2) {
            cnt++;
        }

        // 计算每年天数总和
        for (int i = 1; i < year; i++) {
            if (isLeapYear(i)) {
                cnt += 366;
            }
            else {
                cnt += 365;
            }
        }

        return cnt;
    }

    public int daysBetweenDates(String date1, String date2) {
        int days1 = convertDateToInt(date1);
        int days2 = convertDateToInt(date2);

        return Math.abs(days1 - days2);
    }

}

